package com.glwan.fixedassetapp.ui.home.locateTag;

import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.glwan.fixedassetapp.Adapter.ListableAdapter;
import com.glwan.fixedassetapp.Adapter.ListableAdapterCustomHandler;
import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.common.CommonConstant;
import com.glwan.fixedassetapp.common.DatabaseConstant;
import com.glwan.fixedassetapp.components.SelectView;
import com.glwan.fixedassetapp.utils.CommonUtil;
import com.glwan.fixedassetapp.utils.DatabaseUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchLocateTagActivity extends AppCompatActivity implements ListableAdapterCustomHandler {

    Button confirmSearch;
    Button resetSearch;
    EditText searchFdYzCardCode;
    EditText searchFdYzCardName;
    EditText searchRFID;
    SelectView searchFdCardCategoryName;
    EditText searchFdLocation;
    SelectView searchFdDutyDeptName;
    EditText searchFdDutyPersonName;
    Spinner searchUseStatus;
    Spinner searchStatus;

    View searchLayout;
    LinearLayout expandLinearLayout;
    TextView tvExpandIcon;
    TextView tvExpandText;
    private Map<String, Integer> groupTextViewMap = new HashMap<>();
    private List<Map<String, Object>> parentList = new ArrayList<>();
    private ListView listView;
    private ListableAdapter listableAdapter;
    private int currentCount = 0;
    private long totalCount;
    private boolean canScroll;
    private LinearLayout pullLoading;
    private LinearLayout noMoreData;
    private boolean initStatus = true;
    private String selection = null;
    private List<String> selectionArgs = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_tag_locate);
        Toolbar toolbar = findViewById(R.id.moreToolbar);
        setSupportActionBar(toolbar);

        setTitle(getString(R.string.locateTag));

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        initData();
//        LinearLayout listViewLinearLayout = findViewById(R.id.listViewLinearLayout);


        searchLayout = findViewById(R.id.searchLayout);
        expandLinearLayout = findViewById(R.id.expandLinearLayout);
        tvExpandIcon = findViewById(R.id.tvExpandIcon);
        tvExpandText = findViewById(R.id.tvExpandText);

        expandLinearLayout.setOnClickListener(this::triggerExpand);

    }

    private void triggerExpand(View view) {
        int visibility = searchLayout.getVisibility();
        if (visibility == View.GONE) {
            searchLayout.setVisibility(View.VISIBLE);
            tvExpandIcon.setBackground(getDrawable(R.drawable.up));
            tvExpandText.setText("关闭");
        } else {
            searchLayout.setVisibility(View.GONE);
            tvExpandIcon.setBackground(getDrawable(R.drawable.down));
            tvExpandText.setText("展开");
        }
    }

    //返回主界面
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    private SearchLocateTagActivity getActivity() {
        return this;
    }

    private void initData() {

        View loadingMore = LayoutInflater.from(this).inflate(R.layout.loading_more, null);
        pullLoading = loadingMore.findViewById(R.id.pullLoading);
        noMoreData = loadingMore.findViewById(R.id.noMoreData);

        groupTextViewMap.put("fdId", R.id.fdId);
        groupTextViewMap.put("sortNo", R.id.sortNo);
        groupTextViewMap.put("fdYzCardCode", R.id.fdYzCardCode);
        groupTextViewMap.put("fdYzCardName", R.id.fdYzCardName);
//        groupTextViewMap.put("fdYzCardId", R.id.fdYzCardId);
//        groupTextViewMap.put("fdSize", R.id.fdSize);
        groupTextViewMap.put("fdCardCategoryName", R.id.fdCardCategoryName);
        groupTextViewMap.put("fdLocation", R.id.fdLocation);
        groupTextViewMap.put("fdDutyDeptName", R.id.fdDutyDeptName);
        groupTextViewMap.put("fdDutyPersonName", R.id.fdDutyPersonName);
        groupTextViewMap.put("fdSourceQuantity", R.id.fdSourceQuantity);
        groupTextViewMap.put("fdPurchaseTime", R.id.fdPurchaseTime);
        groupTextViewMap.put("fdUseStatus", R.id.fdUseStatus);
        groupTextViewMap.put("reason", R.id.reason);
        groupTextViewMap.put("status", R.id.status);

        listView = findViewById(R.id.listView);

        listableAdapter = new ListableAdapter(
                getActivity(),
                parentList,
                groupTextViewMap,
                R.layout.fgw_offline_product_item);
        listView.setAdapter(listableAdapter);


        listView.setOnItemLongClickListener((adapterView, view, i, l) -> {
            Map<String, Object> item = (Map<String, Object>) listableAdapter.getItem(i);

            Map<String, Object> map = new HashMap<>();
            map.put("tagPatternValue", item.get("fdId"));
            CommonUtil.toastShow(getActivity(), "已选中资产 \n" +
                    "资产编号：" + item.get("fdYzCardCode") + "\n" +
                    "资产名称：" + item.get("fdYzCardName") + "", CommonUtil.SUCCESS, true);
            CommonUtil.startActivity(getActivity(), LocateTagActivity.class, map, false);
            return true;
        });


//        dialog = new Dialog(getActivity());
//        LayoutInflater inflater= LayoutInflater.from(getActivity());
//        View dialogView = inflater.inflate(R.layout.fgw_offline_product_search_dialog, null);
//        dialog.setContentView(dialogView);
//        dialog.create();
//
//        // 获取对话框的窗口对象
//        Window window = dialog.getWindow();
//        if (window != null) {
//            // 设置对话框在屏幕右上方
//            window.setGravity(Gravity.TOP | Gravity.END);
//
//            // 设置对话框宽度为屏幕宽度的90%
//            WindowManager.LayoutParams layoutParams = window.getAttributes();
//            layoutParams.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.9);
//            window.setAttributes(layoutParams);
//        }
//        dialog.setTitle("搜索条件");

        confirmSearch = findViewById(R.id.btSearchConfirm);
        confirmSearch.setOnClickListener(view -> {
            initStatus = true;
            currentCount = 0;

            //清空条件
            selection = "";
            selectionArgs.clear();

            setSearchSelection("FD_YZ_CARD_CODE", searchFdYzCardCode);
            setSearchSelection("FD_YZ_CARD_NAME", searchFdYzCardName);
//            setSearchSelection("FD_ID", searchRFID);
            setSearchSelection("FD_LOCATION", searchFdLocation);
//            setSearchSelection("FD_DUTY_PERSON_NAME", searchFdDutyPersonName);

            setSearchSpinnerSelection("FD_CARD_CATEGORY_NAME", searchFdCardCategoryName);
            setSearchSpinnerSelection("FD_DUTY_DEPT_NAME", searchFdDutyDeptName);
//            setSearchSpinnerSelection("FD_USE_STATUS", searchUseStatus);

            int searchStatusPosition = searchStatus.getSelectedItemPosition();
            String searchStatusColumnName = "STATUS";
            if (searchStatusPosition == 1) {
                selection += " AND " + searchStatusColumnName + " = 0 ";
            } else if (searchStatusPosition == 2) {
                selection += " AND " + searchStatusColumnName + " = 4 ";
            } else if (searchStatusPosition == 3) {
                selection += " AND " + searchStatusColumnName + " = 5 ";
            }
            Log.i("selection", selection);
            Log.i("selectionArgs", String.valueOf(selectionArgs.size()));
            queryData();
        });

        resetSearch = findViewById(R.id.btResetSearch);
        resetSearch.setVisibility(View.GONE);
        resetSearch.setOnClickListener(view -> {
//            searchFdDutyDeptName.setSelectedItem(null);
        });


//        LinearLayout searchRFIDLinearLayout = findViewById(R.id.searchRFIDLinearLayout);
//        searchRFIDLinearLayout.setVisibility(View.GONE);

        LinearLayout searchStatusLinearLayout = findViewById(R.id.searchStatusLinearLayout);
        searchStatusLinearLayout.setVisibility(View.GONE);

        searchFdYzCardCode = findViewById(R.id.searchFdYzCardCode);
        searchFdYzCardName = findViewById(R.id.searchFdYzCardName);
//        searchRFID = findViewById(R.id.searchRFID);
        searchFdCardCategoryName = findViewById(R.id.searchFdCardCategoryName);
        searchFdLocation = findViewById(R.id.searchFdLocation);
        searchFdDutyDeptName = findViewById(R.id.searchFdDutyDeptName);
//        searchFdDutyDeptName.setOnItemSelectedListener(new OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(View view, int position, long id) {
//                Log.i("searchFdDutyDeptName", String.valueOf(searchFdDutyDeptName.getSelectedItem()));
//            }
//
//            @Override
//            public void onNothingSelected() {
//
//            }
//        });
//        searchFdDutyPersonName = findViewById(R.id.searchFdDutyPersonName);
//        searchUseStatus = findViewById(R.id.searchUseStatus);
        searchStatus = findViewById(R.id.searchStatus);
        searchStatus.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, new String[]{"全部", "待盘点", "已盘点", "异常盘点"}));

//        queryData();
        queryConditionData();
    }

    private void setSearchSelection(String columnName, EditText editText) {
        String value = String.valueOf(editText.getText());
        if (!("null".equals(value) || "".equals(value))) {
            selection += " AND " + columnName + " LIKE '%" + value + "%' ";
        }
    }

    private void setSearchSpinnerSelection(String columnName, View view) {
        String value = "";
//        if(view instanceof Spinner){
//            Spinner spinner = (Spinner)view;
//            if(spinner.getSelectedItemPosition() == 0){
//                return;
//            }
//            value = String.valueOf(spinner.getSelectedItem());
//        }
//        else if(view instanceof SearchableSpinner){
//            SearchableSpinner searchableSpinner = (SearchableSpinner)view;
//            value = String.valueOf(searchableSpinner.getSelectedItem());
//        }
//        if(!("null".equals(value) || "".equals(value))){
//            selection += " AND " + columnName + " = ? ";
//            selectionArgs.add(value);
//        }

        if (view instanceof Spinner) {
            Spinner spinner = (Spinner) view;
            if (spinner.getSelectedItemPosition() == 0) {
                return;
            }
            value = String.valueOf(spinner.getSelectedItem());
        } else if (view instanceof SelectView) {
            SelectView selectView = (SelectView) view;
            if (selectView.getSelectedItemPosition() == 0) {
                return;
            }
            value = String.valueOf(selectView.getSelectTextValue());
        }
        if (!("null".equals(value) || "".equals(value))) {
            selection += " AND " + columnName + " = ? ";
            selectionArgs.add(value);
        }
    }

    private String getStatusValue(RadioGroup v) {
        String s = ((RadioButton) v.findViewById(v.getCheckedRadioButtonId())).getText().toString();
        return getString(R.string.notCounted).equals(s) ? "0" : getString(R.string.counted).equals(s) ? "4" : "5";
    }

    private void queryData() {
        CommonUtil.openProgressDialog(getActivity(), getString(R.string.loading));
        parentList.clear();
        runOnUiThread(() -> {
            listableAdapter.notifyDataSetChanged();
        });
        String[] selectionArgArray;
        if (selectionArgs.size() > 0) {
            selectionArgArray = new String[selectionArgs.size()];
            selectionArgs.toArray(selectionArgArray);
        } else {
            selectionArgArray = new String[0];
        }
        if (initStatus) {
            Cursor totalCursor = DatabaseUtil.rawQuery("SELECT COUNT(1) FROM " + DatabaseConstant.OFFLINE_INVENTORY_TASK_ITEM + " WHERE 1 = 1 " + ((selection == null || "".equals(selection) ? "" : selection)), selectionArgArray);
            totalCursor.moveToFirst();
            totalCount = totalCursor.getLong(0);
            initStatus = false;
        }

        if (totalCount > 0) {
            //查询结果
            String[] columnNames = new String[]{
                    "FD_ID",
                    "FD_YZ_CARD_NAME",
                    "FD_YZ_CARD_ID",
                    "FD_YZ_CARD_CODE",
                    "FD_SIZE",
                    "FD_LOCATION",
                    "FD_CARD_CATEGORY_NAME",
                    "FD_DUTY_DEPT_NAME",
                    "FD_DUTY_PERSON_NAME",
                    "FD_PURCHASE_TIME",
                    "FD_SOURCE_QUANTITY",
                    "FD_USE_STATUS",
                    "REASON",
                    "STATUS"};
            Cursor cursor = DatabaseUtil.querySQL(
                    DatabaseConstant.OFFLINE_INVENTORY_TASK_ITEM,
                    columnNames,
                    selection == null || "".equals(selection) ? "" : " 1 = 1 " + selection,
                    selectionArgArray,
                    null,
                    currentCount + "," + CommonConstant.INIT_LIST_VIEW_SIZE);
            while (cursor.moveToNext()) {
                Map<String, Object> map = new HashMap<>();

                for (String s : columnNames) {
                    int columnIndex = cursor.getColumnIndex(s);
                    if (columnIndex >= 0) {

                        String objectName = DatabaseUtil.convertName(s);
                        String value = cursor.getString(columnIndex);

                        map.put(objectName, value);

                    }
                }
                parentList.add(map);
            }

            Log.i("parentList", parentList.toString());

            runOnUiThread(() -> {
                listableAdapter.notifyDataSetChanged();
                setScrollListener(true);
                triggerExpand(expandLinearLayout);
                CommonUtil.cancelProgressDialog(getActivity());
            });
        } else {
            CommonUtil.cancelProgressDialog(getActivity());
        }


    }

    private void setScrollListener(boolean open) {
        if (open) {
            listView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                        Log.i("当前列表总行数", String.valueOf(view.getLastVisiblePosition()));
                        Log.i("list大小", String.valueOf(parentList.size()));
                        Log.i("totalCount", String.valueOf(totalCount));
                        Log.i("currentCount", String.valueOf(currentCount));
                        if (view.getLastVisiblePosition() == parentList.size() - 1) {
                            if (view.getLastVisiblePosition() >= totalCount - 1) {
                                pullLoading.setVisibility(View.GONE);
                                noMoreData.setVisibility(View.VISIBLE);
                                Log.i("currentCount！！！", String.valueOf(currentCount));

                            } else {
                                pullLoading.setVisibility(View.VISIBLE);
                                noMoreData.setVisibility(View.GONE);
                                setScrollListener(false);
                                currentCount = currentCount + CommonConstant.INIT_LIST_VIEW_SIZE;
                                Log.i("canScrollCurrentCount", String.valueOf(currentCount));
                                queryData();

                            }
                        }

                    }
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                }
            });
        } else {
            listView.setOnScrollListener(null);
        }
    }

    @Override
    public void customHandler(String key, TextView textView) {
        String s = textView.getText().toString();
        if ("status".equals(key)) {
            if (Integer.parseInt(s) == 0) {
                textView.setTextColor(getColor(R.color.red));
                textView.setText(getString(R.string.notCounted));
            } else if (Integer.parseInt(s) == 4) {
                textView.setTextColor(getColor(R.color.green));
                textView.setText(getString(R.string.counted));
            } else {
                textView.setTextColor(getColor(R.color.orange));
                textView.setText(getString(R.string.errorCounted));
            }
        }
    }

    /**
     * 查询搜索条件数据
     */
    private void queryConditionData() {

        String[] columnNames = {"notCountedCount", "countedCount", "errorCountedCount", "allCardCategoryName", "allDeptName", "allUseStatus"};
        Cursor countCursor = DatabaseUtil.rawQuery("SELECT " +
                "SUM(CASE WHEN STATUS = 0 THEN 1 ELSE 0 END) AS " + columnNames[0] + ", " +
                "SUM(CASE WHEN STATUS = 4 THEN 1 ELSE 0 END) AS " + columnNames[1] + ", " +
                "SUM(CASE WHEN STATUS = 5 THEN 1 ELSE 0 END) AS " + columnNames[2] + ", " +
                "(\n" +
                "        SELECT GROUP_CONCAT(FD_CARD_CATEGORY_NAME, ';')\n" +
                "        FROM (\n" +
                "            SELECT DISTINCT FD_CARD_CATEGORY_NAME\n" +
                "            FROM OFFLINE_INVENTORY_TASK_ITEM\n" +
                "        )\n" +
                "    ) AS " + columnNames[3] + ", \n" +
                "(\n" +
                "        SELECT GROUP_CONCAT(FD_DUTY_DEPT_NAME, ';')\n" +
                "        FROM (\n" +
                "            SELECT DISTINCT FD_DUTY_DEPT_NAME\n" +
                "            FROM OFFLINE_INVENTORY_TASK_ITEM\n" +
                "        )\n" +
                "    ) AS  " + columnNames[4] + ", \n" +
                "    (\n" +
                "        SELECT GROUP_CONCAT(FD_USE_STATUS, ';')\n" +
                "        FROM (\n" +
                "            SELECT DISTINCT FD_USE_STATUS\n" +
                "            FROM OFFLINE_INVENTORY_TASK_ITEM\n" +
                "        )\n" +
                "    ) AS  " + columnNames[5] + " \n" +
                "FROM " + DatabaseConstant.OFFLINE_INVENTORY_TASK_ITEM, null);

        while (countCursor.moveToNext()) {
            for (String s : columnNames) {
                int columnIndex = countCursor.getColumnIndex(s);
                if (columnIndex >= 0) {

                    String value = countCursor.getString(columnIndex);
                    if ("".equals(value) || value == null) {
                        value = "0";
                    }

//                    if ("notCountedCount".equals(s)) {
//                        ((TextView) findViewById(R.id.notCountedCount)).setText(value);
//                    }
//                    if ("countedCount".equals(s)) {
//                        ((TextView) findViewById(R.id.countedCount)).setText(value);
//                    }
//                    if ("errorCountedCount".equals(s)) {
//                        ((TextView) findViewById(R.id.errorCountedCount)).setText(value);
//                    }
                    if ("allCardCategoryName".equals(s)) {
                        setSpinnerValue(searchFdCardCategoryName, value);
                    }
                    if ("allDeptName".equals(s)) {
                        setSpinnerValue(searchFdDutyDeptName, value);
                    }
                    if ("allUseStatus".equals(s)) {
                        setSpinnerValue(searchUseStatus, value);
                    }

                }
            }
        }
    }

    private void setSpinnerValue(View view, String value) {
        if (!"null".equals(value)) {
            String[] split = value.split(";");
            if (split.length > 0) {
//                String[] newSplit = new String[split.length + 1];
//                newSplit[0]="全部";
//                System.arraycopy(split, 0, newSplit, 1, split.length);
                String[] newSplit = new String[split.length + 1];
                newSplit[0] = "全部";
                System.arraycopy(split, 0, newSplit, 1, split.length);
                if (view instanceof Spinner) {
                    ((Spinner) view).setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, newSplit));
                } else if (view instanceof SelectView) {
                    SelectView selectView = (SelectView) view;
                    selectView.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, newSplit));
                    selectView.setSelectedItem(0);
                }
            }
        }
    }

}
